﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IEC
{
    //option.ini
    class GameOption
    {
        Dictionary<string, string> pairs = new Dictionary<string, string>();
        public GameOption()
        {
        }

        public void LoadOption()
        {
            if (MainWindow.config.GetStatus() == GameConfig.ConfigStatus.OK)
            {
                pairs.Clear();
                var reg = new System.Text.RegularExpressions.Regex("([^=]+)=(.*)$");
                foreach (string line in System.IO.File.ReadAllLines(MainWindow.config.GetOptionPath()))
                {
                    var match = reg.Match(line.TrimEnd('\n', '\r'));
                    if (match.Success)
                    {
                        pairs.Add(match.Groups[1].Value, match.Groups[2].Value);
                    }
                }
            }
        }

        //return error message. null if success
        public string SaveOption()
        {
            if (MainWindow.config.GetStatus() == GameConfig.ConfigStatus.OK)
            {
                StringBuilder sb = new StringBuilder("[Options]\n");
                foreach (KeyValuePair<string, string> k in pairs)
                {
                    sb.Append(k.Key).Append("=").Append(k.Value).AppendLine();
                }
                try
                {
                    System.IO.File.WriteAllText(MainWindow.config.GetOptionPath(), sb.ToString());
                    return null;
                }
                catch (Exception e)
                {
                    return e.Message;
                }
            }
            else
            {
                return "游戏配置异常";
            }
        }

        public Dictionary<string,string> Dict { get { return pairs; } }
    }
}
